$(function () {
    //定义全局变量
    window.pageSize = 5;
    window.pageNum = 1;
    window.keyword = "";
    //显示数据
    showPage();
});

function showPage() {
    $.ajax({
        url: "/role/search/by/keyword.json",
        type: "post",
        data: {
            "pageNum": window.pageNum,
            "pageSize": window.pageSize,
            "keyword": window.keyword
        },
        dataType: "json",
        success: function (result) {
            if (result.result == "SUCCESS") {
                //解析数据
                $("#roleTableBody").empty();
                // 获取数据集合
                var list = result.data.list;
                // 判断list是否有效
                if (list == null || list.length == 0) {
                    $("#roleTableBody")
                        .append("<tr><td colspan='4' style='text-align:center;'>没有查询到数据！</td></tr>");

                    return;
                }
                for (var i = 0; i < list.length; i++) {
                    var role = list[i];

                    //数据
                    var numberTd = "<td>" + (i + 1) + "</td>";
                    var checkBoxTd = "<td><input class='itemBox' roleid='" + role.id + "' type='checkbox'></td>";
                    var roleNameTd = "<td>" + role.name + "</td>";

                    //按钮
                    /*  var checkBtn = "<button type='button' class='btn btn-success btn-xs'><i class=' glyphicon glyphicon-check'></i></button>";*/
                    var checkBtn = "<button roleId='" + role.id + "' type='button' class='btn btn-success btn-xs checkBtn'>" +
                        "<i class=' glyphicon glyphicon-check'></i></button>";

                    /* var pencilBtn = "<button type='button' class='btn btn-primary btn-xs'>" +
                         "<i class=' glyphicon glyphicon-pencil'></i></button>";*/
                    var pencilBtn = "<button roleId='" + role.id + "' type='button' class='btn btn-primary btn-xs editBtn'>" +
                        "<i class=' glyphicon glyphicon-pencil'></i></button>";

                    /*  var removeBtn = "<button type='button' class='btn btn-danger btn-xs'>" +
                          "<i class=' glyphicon glyphicon-remove'></i></button>";*/
                    var removeBtn = "<button roleId='" + role.id + "' type='button' class='btn btn-danger btn-xs removeBtn'><i class=' glyphicon glyphicon-remove'></i></button>";

                    var btnTd = "<td>" + checkBtn + " " + pencilBtn + " " + removeBtn + "</td>";

                    var tr = "<tr>" + numberTd + checkBoxTd + roleNameTd + btnTd + "</tr>";

                    // 将前面拼好的HTML代码追加到#roleTableBody中
                    $("#roleTableBody").append(tr);
                }

                //显示分页导航
                initPagination(result.data);
            } else {
                layer.msg(result.message);
            }
        }
    });
}

//声明函数封装导航条初始化操作
function initPagination(pageInfo) {

    // 声明变量存储分页导航条显示时的属性设置
    var paginationProperties = {
        num_edge_entries: 3,        //边缘页数
        num_display_entries: 5,      //主体页数
        callback: pageselectCallback, //回调函数
        items_per_page: window.pageSize,    //每页显示数据数量，就是pageSize
        current_page: (window.pageNum - 1),//当前页页码
        prev_text: "上一页",       //上一页文本
        next_text: "下一页"        //下一页文本
    };
    // 显示分页导航条
    $("#Pagination").pagination(pageInfo.total, paginationProperties);
}

// 在每一次点击“上一页”、“下一页”、“页码”时执行这个函数跳转页面
function pageselectCallback(pageIndex, jq) {
    // pageIndex从0开始，pageNum从1开始
    window.pageNum = pageIndex + 1;
    // 跳转页面     然后在导航栏显示输入的查询信息
    showPage();
    return false;
}

//关键字查询
$("#searchBtn").click(function () {
    //获取文本框的输入的数据
    var keyword = $("#keywordInput").val();
    //验证是否为空
    if (keyword.length == 0) {
        layer.msg("关键字不能为空!");
        return;
    }
    //更新全局变量
    window.keyword = keyword;
    //刷新数据
    showPage();
})

//全选/全不选

$("#summaryBox").click(function () {
    //获取当前checkBox的选中状态
    var currentStatus = this.checked;
    //2.设置itembox的选中状态  prop true  或   false
    $(".itemBox").prop("checked", currentStatus);
})


$("#batchRemoveBtn").click(function () {
    // 获取被选中的itemBox数组长度
    var length = $(".itemBox:checked").length;

    // 如果长度为0，说明没有选择itemBox
    if (length == 0) {
        layer.msg("请至少选择一条！");
        return;
    }
});


//5．在弹出的模态框中显示confirm信息
$("#batchRemoveBtn").click(function () {
    //获取被选中的itemBox数组长度
    var length = $(".itemBox:checkbox").length;
    //如果为0则没有被选中
    if (length == 0) {
        layer.msg("请至少选中一条数据!")
        return;
    }
    //在全局作用域内创建roleArray
    window.roleIdArray = new Array();

    //遍历$(itemBox:checked)
    $(".itemBox:checked").each(function () {
        //通过checkBox的roleid属性获取roleId值
        var roleId = $(this).attr("roleid");
        //存入数组
        window.roleIdArray.push(roleId);
    })
    // 调用函数打开模态框
    showRemoveConfirmModal();
})

function showRemoveConfirmModal() {
    //将模态框显示出来
    $("#confirmModal").modal("show");
    //显示要删除的数据
    var requestBody = JSON.stringify(window.roleIdArray);
    //发送ajax请求
    var ajaxResult = $.ajax({
        url: "/role/get/list/by/id/list",
        type: "post",
        data: requestBody,
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        success: function (ajaxResult) {
            if (ajaxResult.result == "SUCCESS") {
                $("#confirmModalTableBody").empty();
                //填充 confirmModalTableBody
                var roleList = ajaxResult.data;
                for (var i = 0; roleList.length; i++) {
                    //5.获取角色相关数据
                    var role = roleList[i];
                    var id = role.id;
                    var name = role.name;

                    var $tr = "<tr><td>" + id + "</td><td>" + name + "</td><tr/>";
                    //进行数据填充
                    $("#confirmModalTableBody").append($tr);
                }
            } else {
                layer.msg(ajaxResult.message);
                return null;
            }
        }
    })
}

//10．绑定单击响应函数  绑定ajax删除页面的ok
$("#confirmModalBtn").click(function () {
    //把自己定义的那个id转换成 json格式输出
    var requestBody = JSON.stringify(window.roleIdArray);
    $.ajax({
        url: "/role/batch/remove",
        type: "post",
        data: requestBody,
        contentType: "application/json;charset=UTF-8",
        dataType: "json",
        success: function (ajaxresult) {
            var result = ajaxresult.result;
            if (result == "SUCCESS") {
                layer.msg("删除成功!");
                //然后调用 重新分页
                showPage();
            } else {
                layer.msg("删除失败!" + ajaxresult.message);
            }
            //关掉模态框  不管成功与否
            $("#confirmModal").modal("hide");
        }
    })
})

//三十二、角色维护-单条删除
//单条删除
$("#roleTableBody").on("click", ".removeBtn", function () {
    //获取当前记录的roleId
    var roleId = $(this).attr("roleId");
    //存入全局变量数组
    window.roleIdArray = new Array();
    window.roleIdArray.push(roleId);
    //打开模态框
    showRemoveConfirmModal();
})

//绑定新增单机事件
$("#addBtn").click(function () {
    // alert("aaa...");
    //打开增加模态框
    $("#addModal").modal("show");
});


//确定增加
$("#addModalBtn").click(function () {
    //收集文本框内容
    var roleName = $.trim($("#roleNameInput").val());
    if (roleName == "") {
        layer.msg("请输入有效的字符!");
        return;
    }

    $.ajax({
        url: "/role/save/role",
        type: "post",
        data: {
            "roleName": roleName
        },
        dataType: "json",
        success: function (ajaxResult) {
            var result = ajaxResult.result;
            if (result = "SUCCESS") {
                layer.msg("操作成功!");
                //跳转到最后一页 因为增加成功数据在最后一页
                window.pageNum = 9999999;
                //进行分页
                showPage();
                $("#roleNameInput").empty();
            } else {
                layer.msg(ajaxResult.message);
            }
            //关闭模态框
            $("#addModal").modal("hide");
        }
    })
})
//4．绑定单击响应函数
$("#roleTableBody").on("click", ".editBtn", function () {
    //获取当前按钮的roleId
    window.roleId = $(this).attr("roleId");
    //获取roleName
    var roleName = $(this).parents("tr").children("td:eq(2)").text();
    //显示roleName
    $("#roleNameInputEdit").val(roleName);
    //打开模态框
    $("#editModal").modal("show");
})

//修改
$("#editModalBtn").click(function () {
    //收集文本框内容
    var roleName = $.trim($("#roleNameInputEdit").val());
    if (roleName == "") {
        layer.msg("请输入有效的角色名称!");
        return;
    }

    $.ajax({
        url: "/role/update/role",
        type: "post",
        data: {
            id: window.roleId,
            name: roleName
        },
        dataType: "json",
        success: function (ajaxResult) {
            var result = ajaxResult.result;
            if (result = "SUCCESS") {
                layer.msg("操作成功!");
                //进行分页
                showPage();
            } else {
                layer.msg(ajaxResult.message);
            }
            //关闭模态框
            $("#editModal").modal("hide");
        }
    })
})


//绑定修改权限按钮单击事件
$("#roleTableBody").on("click", ".checkBtn", function () {

    //将角色id存入全局变量
    window.roleId = $(this).attr("roleId");
    console.log(window.roleId);
    $("#roleAssignAuthModal").modal("show");
    initPagination();
})

function initPagination() {
    var setting = {
        "data": {
            "simpleData": {
                "enable": true,//启用简单JSON功能
                "pIdKey": "categoryId"//设置显示节点名称的实体类属性名
            },
            "key": {
                "name": "title"//设置当前节点父节点的属性名
            }
        },
        "check": {
            "enable": true//设置树形节点前显示checkbox
        }
    };

    //获取json数据

    $.ajax({
        url: "/assign/get/all/auth",
        type: "post",
        dataType: "json",
        success: function (ajaxResult) {
            if (ajaxResult.result == "FAILED") {
                layer.msg(ajaxResult.message);
                rturn;
            }
            var zNodes = ajaxResult.data;
            // 3.初始化树形结构
            $.fn.zTree.init($("#treeDemo"), setting, zNodes);
            //展开所有节点
            $.fn.zTree.getZTreeObj("treeDemo").expandAll(true);

            //回显已分配权限
            goBackAuth();
        }
    })
}

//4.5.2根据以前分配的信息勾选树形节点
//回显已分配的权限
function goBackAuth() {
    $.ajax({
        url: "/assign/get/assigned/auth/id/list",
        type: "post",
        dataType: "json",
        data: {
            "roleId": window.roleId,
            "random": Math.random()
        },
        success: function (ajaxResult) {
            if (ajaxResult.result == "FAILED") {
                layer.msg(ajaxResult.message);
                return;
            }

            //显示已分配的权限
            var authIdList = ajaxResult.data;
            //6.使用authIdList勾选相对应的树形节点
            //遍历authIdList
            for (var i = 0; i < authIdList.length; i++) {
                var authId = authIdList[i];
                //根据authId查询到一个具体的树形节点
                //key:查询节点的属性名
                //value:查询节点的属性值,这里使用authId
                var key = "id";
                var treeNode = $.fn.zTree.getZTreeObj("treeDemo").getNodeByParam(key, authId);
                //勾选找到的节点
                //treeNode:当前要勾选的节点
                //true:设置为勾选状态
                //false:表示不联动
                $.fn.zTree.getZTreeObj("treeDemo").checkNode(treeNode, true, false);
            }
        }
    })
}
/*
//4.6执行分配
$("#roleAssignAuthBtn").click(function () {
    var authIdArray = new Array();
    //掉用zNodes方法获取当前被选中的节点
    var checkedNodes = $.fn.zTree.getZTreeObj("treeDemo").getCheckedNodes();

    for (var i = 0; i < checkedNodes.length; i++) {
        //获取具体的一个节点
        var node = checkedNodes[i];
        //获取当前节点的id属性
        var authId = node.id;
        //将authId存入数组
        authIdArray.push(authId);
    }
    var requestBody = {"roleIdList": [window.roleId], "authIdList": authIdArray};
    console.log(requestBody);
/!*    //发送请求
    $.ajax({
            url: "/assign/do/assign",
            type: "post",
            dataType: "json",
            data: JSON.stringify(requestBody),
         "contentType": "application/json;charset=UTF-8",
        success:function (ajaxResult) {
            if(ajaxResult.result=="SUCCESS"){
                layer.msg("成功!")
                return;
            }else{
                layer.msg("失败!");
            }
        }
        }
    )
    $("#roleAssignAuthModal").modal("hide");*!/
// 发送请求
    $.ajax({
        "url": "/assign/do/assign",
        "type": "post",
        "data": JSON.stringify(requestBody),
        "contentType": "application/json;charset=UTF-8",
        "dataType": "json",
        success:function (ajaxResult) {
            if(ajaxResult.result == "SUCCESS") {
                layer.msg("操作成功！");
            }

            if(ajaxResult.result == "FAILED") {
                layer.msg(ajaxResult.message);
            }
            $("#roleAssignAuthModal").modal("hide");
        }
    });
})*/


//分配权限
$("#roleAssignAuthBtn").click(function () {
    var authIdArray = new Array();
    // 调用zTreeObj的方法获取当前已经被勾选的节点
    var checkedNodes=$.fn.zTree.getZTreeObj("treeDemo").getCheckedNodes();

    for(var i = 0; i < checkedNodes.length; i++) {
        // 获取具体的一个节点
        var node = checkedNodes[i];
        // 获取当前节点的id属性
        var authId = node.id;
        // 将authId存入数组
        authIdArray.push(authId);
    }
    var requestBody = {"roleIdList":[window.roleId], "authIdList": authIdArray};

    // 发送请求
    $.ajax({
        "url": "/assign/do/assign",
        "type": "post",
        "data": JSON.stringify(requestBody),
        "contentType": "application/json;charset=UTF-8",
        "dataType": "json",
        success:function (ajaxResult) {
            if(ajaxResult.result == "SUCCESS") {
                layer.msg("操作成功！");
            }

            if(ajaxResult.result == "FAILED") {
                layer.msg(ajaxResult.message);
            }
            $("#roleAssignAuthModal").modal("hide");
        }
    });

});

